package com.zz.ui_demo_wedgit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ListView2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view2);
        //查找联系人权限，是否已经授权
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) !=
                PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS}, 1);
        }else{
            readContacts();//读取联系人
        }
    }
//请求回调权限的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 1){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                readContacts();
            }else{
                Toast.makeText(this, "未获得相应权限", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void readContacts() {
        ListView lvContacts = findViewById(R.id.lv_contact);
        //读取联系人的标准模式  游标.---数据库
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null, null, null, null);
        String[] from = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER};
        int[] to = new int[]{R.id.tv_display_name,R.id.tv_phone_number};
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_contact, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        lvContacts.setAdapter(adapter);
        lvContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor c = (Cursor)lvContacts.getItemAtPosition(position);
                int index = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                String msg = c.getString(index);
                Toast.makeText(ListView2Activity.this, msg, Toast.LENGTH_SHORT).show();

            }
        });
    }
}